package fr.sportcom.sportcom.controller;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import fr.sportcom.sportcom.R;
import fr.sportcom.sportcom.SportComApplication;
import fr.sportcom.sportcom.adapter.EventListAdapter;
import fr.sportcom.sportcom.model.AdsManager;
import fr.sportcom.sportcom.model.CEvent;
import fr.sportcom.sportcom.model.CSport;
import fr.sportcom.sportcom.model.CustomHttpClient;

import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.text.Html;
import android.text.Spanned;

public class EventListActivity extends Activity implements OnItemClickListener {

	//// EXTRA
	// En entr�e :
	public final static String EXTRA_ACTION = "fr.sportcom.sportcom.extra.ela.ACTION";
	public final static String EXTRA_SPORT = "fr.sportcom.sportcom.extra.ela.SPORT";

	// Valeur d'ACCTION:
	public final static int USER = 1, SPORT = 2;

	private ListView listView;
	private View mloadingStatusView;

	private int pAction;
	private int pUserId = 0;
	private int pCurentUser = 0;
	private CSport selectedSport;
	private ArrayList<CEvent> lEvent = new ArrayList<CEvent>();
	boolean mNeedRefreshAtBack = false;

	public static Intent prepareIntent(Context context, int action, CSport sport) {
		return new Intent(context, EventListActivity.class)
		.putExtra(EXTRA_ACTION, action)
		.putExtra(EXTRA_SPORT, sport);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_event_list);
		setContentView(R.layout.sponso_layout);
		View appContent = LayoutInflater.from(this).inflate(
				R.layout.activity_event_list, 
				(ViewGroup) this.findViewById(R.id.app_content), 
				false);
		((LinearLayout)this.findViewById(R.id.app_content)).addView(appContent);
		AdsManager.displayAds(this);
		
		// On recupere l'utulisateur connect�
		pCurentUser = ((SportComApplication) (this.getApplication())).getLoggedUser().getId();
		
		// On r�cup�re l'intent
		Intent i = getIntent();
		pAction = i.getIntExtra(EXTRA_ACTION, USER);
		selectedSport = i.getParcelableExtra(EXTRA_SPORT);
		if(selectedSport == null) {
			selectedSport = new CSport(0, "");
		}
		if(pAction == USER) {
			pUserId = pCurentUser;
		}

		// On place le titre du sport selectionner.
		//TextView title = (TextView)this.findViewById(R.id.textEventTitle);
		if(pAction == SPORT) {
			//title.setText(selectedSport.getName());
			setTitle(selectedSport.getName());
		}

		listView = (ListView) findViewById(R.id.listEvent);
		mloadingStatusView = findViewById(R.id.loading_status_event);

		showProgress(true);
		RefreshListTask mRefresh = new RefreshListTask();
		mRefresh.link(this);
		mRefresh.execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_event_list, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			this.finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
		// Pour test.
		/*Toast.makeText( EventListActivity.this, 
				"El�ment: " + pos + " | id: " + id, 
				Toast.LENGTH_SHORT)
				.show();*/

		// On pr�pare l'activit� avec le param selectionn�.
		Intent intentEvent = new Intent(EventListActivity.this, EventDetailActivity.class);
		//intentEvent.putExtra(SportListActivity.EVENTID, (int)id);
		intentEvent.putExtra(EventDetailActivity.EXTRA_EVENT, lEvent.get(pos));
		startActivity(intentEvent);
		mNeedRefreshAtBack = (lEvent.get(pos).getStatutInvite() == 0);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		AdsManager.displayAds(this);
		if(mNeedRefreshAtBack) {
			showProgress(true);
			RefreshListTask mRefresh = new RefreshListTask();
			mRefresh.link(this);
			mRefresh.execute();
			mNeedRefreshAtBack = false;
		}
	}

	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mloadingStatusView.setVisibility(View.VISIBLE);
			mloadingStatusView.animate().setDuration(shortAnimTime)
			.alpha(show ? 1 : 0)
			.setListener(new AnimatorListenerAdapter() {
				@Override
				public void onAnimationEnd(Animator animation) {
					mloadingStatusView.setVisibility(show ? View.VISIBLE
							: View.GONE);
				}
			});

			listView.setVisibility(View.VISIBLE);
			listView.animate().setDuration(shortAnimTime)
			.alpha(show ? 0 : 1)
			.setListener(new AnimatorListenerAdapter() {
				@Override
				public void onAnimationEnd(Animator animation) {
					listView.setVisibility(show ? View.GONE
							: View.VISIBLE);
				}
			});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mloadingStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			listView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	private class RefreshListTask extends AsyncTask<Void, Void, Boolean> {

		private WeakReference<EventListActivity> mActivity = null;
		private int backStatus = -99;

		@Override
		protected Boolean doInBackground(Void... params) {

			CustomHttpClient request = new CustomHttpClient();
			JSONObject jObj = null;
			ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("userId", ""+pUserId));
			param.add(new BasicNameValuePair("curentUser", ""+pCurentUser));
			param.add(new BasicNameValuePair("sportId", ""+selectedSport.getId()));
			try {
				//Thread.sleep(5000);
				jObj = request.postData("loadEventList", param);
				backStatus = jObj.getInt("back");

				if(backStatus != 0) {
					return false;
				}

				lEvent.clear();
				JSONArray list = jObj.getJSONArray("list");
				for(int i=0; i<list.length(); i++) {
					CSport sportEvent = new CSport(
							list.getJSONObject(i).getInt("spr_id"), 
							list.getJSONObject(i).getString("spr_libelle")
							);

					int id = list.getJSONObject(i).getInt("evt_id");
					String deb = list.getJSONObject(i).getString("evt_debut"); 
					String fin = list.getJSONObject(i).getString("evt_fin");
					double lat = list.getJSONObject(i).getDouble("evt_latitude");
					double lon = list.getJSONObject(i).getDouble("evt_longitude");
					int nbPart = list.getJSONObject(i).getInt("evt_nombreParticipant");
					int idUser = list.getJSONObject(i).getInt("uti_id");
					boolean isPrivate = list.getJSONObject(i).getInt("evt_prive") == 1;
					String description = list.getJSONObject(i).getString("com_contenu");
					Spanned truc = Html.fromHtml(description);
					description = truc.toString();
					int invite = list.getJSONObject(i).getInt("invite");
					
					Address address = null;
					
					Geocoder geo = new Geocoder(EventListActivity.this);
					try {
						List<Address> lAdd;
						lAdd = geo.getFromLocation(lat, lon, 1);
						if(lAdd.size() != 0) {
							address = lAdd.get(0);
						}
					}
					catch (IOException e) {
						e.printStackTrace();
					}
					catch (IndexOutOfBoundsException e) {
						e.printStackTrace();
					}

					CEvent evt = new CEvent(id, 
							deb, 
							fin, 
							lat, 
							lon, 
							address, 
							sportEvent, 
							nbPart,
							idUser,
							isPrivate,
							description,
							invite
							);
					lEvent.add(evt);
				}

			} catch (Exception e) {
				return false;
			}

			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {

			if (!success) {
				Toast.makeText(mActivity.get(), "Une erreur est survenue. "+backStatus, Toast.LENGTH_LONG).show();
			}

			EventListAdapter adapt = new EventListAdapter(mActivity.get(), lEvent);
			listView.setAdapter(adapt);

			listView.setOnItemClickListener(mActivity.get());

			showProgress(false);
		}

		/*@Override
		protected void onPreExecute() {
			showProgress(true);
		};*/

		public void link (EventListActivity pActivity) {
			mActivity = new WeakReference<EventListActivity>(pActivity);
		}
	}
}
